﻿//http启动脚本
"use strict";
const mvc       = require('cosjs.mvc');
const body      = require('body-parser');
const cosjs     = require('cosjs');
const cookie    = require('cookie-parser')
const express   = require('express');

const session_format = {
    "name":{"type":"string","val":""},
    "level":{"type":"int","val":0},
    "auth":{"type":"json","val":{}},
}

module.exports = function(){
    let app = this;
    let root = mvc.config.get("root");
    let debug = mvc.config.get("debug");
    app.defineHandlePrototype("model",mvc.model);
    app.defineHandlePrototype("config",mvc.config);
    app.defineHandlePrototype("library",mvc.library);
    /////////////////////远程跨域//////////////////////
    app.use(function (req,res,next) { res.set("Access-Control-Allow-Origin","*"); next();})
    ///////////////////////模板配置///////////////////
    app.set('views',root + '/views');
    app.set('view engine','ejs');
    app.set('view cache',debug ? false : true);
    ///////////////////////////////////////////
    let urlencoded = body.urlencoded({ extended: true,limit:"100kb" });
    let jsonencoded = body.json({extended: true,limit:"100kb" });
    let session_use = mvc.config.get("session")||{};
    let session_def = {"key":"_gm_sid","format":session_format, "redis":cosjs.pool.get("cache"),"level":handle_session_level,"secret":"szmzbzbzlp","method":'all'}
    let session_opt = Object.assign(session_def,session_use);
    /////////////////////加载用户登录逻辑/////////////////
    let service = mvc.config.get("service");
    if(service && typeof service === 'string'){
        // var stack = new Error().stack
        // console.log( stack )
        require('./service').create.call(app,service);
    }

    /////////////////////游戏后台//////////////////////
    //branch管理//
    let branch_root = root + '/handle/remote/admin/branch';
    let branch_route = {"route":"/b/:branch/*",method:'all',output:'view',"subpath":handle_branch_subpath}
    let branch_server = app.server(branch_root,branch_route,cookie(),urlencoded,jsonencoded);
    branch_server.on('start',ad_branch_start);
    branch_server.on('finish',ad_branch_finish);
    branch_server.session(session_opt);
    branch_server.loader.addPath(root + '/handle/remote/admin/forms','forms');
    //后台其他//
    let remote_root = root + '/handle/remote/admin/base';
    let remote_route = {"route":"*",method:'all',output:'view',"subpath":handle_remote_subpath}
    let remote_server = app.server(remote_root,remote_route,cookie(),urlencoded,jsonencoded);
    remote_server.on('start',ad_base_start);
    remote_server.on('finish', ad_base_finish);
    remote_server.session(session_opt);

    /////////////////////开发者工具//////////////////////
    let dev_root = root + '/handle/remote/dev';
    let dev_route = {"route":"*",method:'all',output:'view',"subpath":handle_dev_subpath}
    let dev_server = app.server(dev_root,dev_route,cookie(),urlencoded,jsonencoded);
    dev_server.on('start',dev_start);
    dev_server.on('finish', dev_finish);
    dev_server.session(session_opt);


    //静态服务器
    app.use(express.static(root + '/wwwroot'));
};

function handle_branch_subpath(){
    this.branch = this.req.params["branch"];
    return this.req.params[0];
}

function handle_remote_subpath(){
    if(this.req.path === '/'){
        return '/login/';
    }
    else {
        return this.req.path
    }
}

function handle_dev_subpath(){
    return this.req.path
}


function handle_session_level(){
    let pubapi = ['/login/','/logout/','/login/verify','/layui/','/game/config','/active/getAllByType','/game/format'];
    if(pubapi.indexOf(this.path) >= 0){
        return 0;
    }
    else{
        return 1;
    }
}

function ad_branch_start(){

 
    //this.branch = this.req.body["branch"];
    let level=this.session.get('level');
    if(level<100){
        let auth=this.session.get('auth');
        if(!auth){
            return this.error('Permission Denied1');
        }
        if(!this.branch){
            return this.error('Branch not exist');
        }
        if(!auth[this.branch].op){
            return this.error('Permission Denied2');
        }
        if(this.req.path.indexOf('save')!=-1){
             if(this.req.path.indexOf('opensdk/save')!=-1){
                    if(!auth[this.branch].dev_edit){
                        return this.error('Permission Denied3');
                }
             }
             else{
                if(!auth[this.branch].op_edit){
                    return this.error('Permission Denied4');
                }

             }
        }

        if(this.req.path.indexOf('income')!=-1||this.req.path.indexOf('welcome')!=-1||this.req.path.indexOf('order')!=-1||this.req.path.indexOf('dau')!=-1){
             if(!auth[this.branch].view){
                    return this.error('Permission Denied5');
             }
        }
    }else{
        return this.error('Permission Denied6');
    }


    if(this.session.get('name')){
        let logModel = this.model.admin("log");
        let _log={name:this.session.get('name'),time:Date.now(),path:this.req.path,post:JSON.stringify(this.req.body),params:JSON.stringify(this.req.params)};
        _log.ip=this.req.ip.replace("::ffff:",'');
        logModel.push(_log);
    }
}

function ad_branch_finish(err,ret){
    let data ={"err":err,"ret":ret};
        data['branch'] = this.branch||'';
    if( this.output === "view" ){
        this.status = 200;
        if(err){
            this.view = "error";
        }
    }
    return data;
}


 
function ad_base_start(){

}


function ad_base_finish(err,ret){
    let data ={"err":err,"ret":ret};
        data['branch'] = this.branch||'';
    if( this.output === "view" ){
        this.status = 200;
        if(err){
            this.view = "error";
        }
    }
    return data;
}



function dev_start(){
    // if(this.session&&this.session.get('auth')){
    //     let level=this.session.get('level');
    //     if(level<100){
    //         let auth=this.session.get('auth');
    //         if(!auth.dev){
    //             return this.error('Permission Denied');
    //         }
    //     }
      
    // }else{
    //     return this.error('Permission Denied');
    // }
    this.branch = this.req.body["branch"];
    let level=this.session.get('level');
    if(level<100){
        let auth=this.session.get('auth');
        if(!auth){
            return this.error('Permission Denied7');
        }
        if(!this.branch){
            return this.error('Branch not exist');
        }
        if(!auth[this.branch].dev){
            return this.error('Permission Denied8');
        }
    }
    else{
        return this.error('Permission Denied9');
    }
}


function dev_finish(err,ret){
    let data ={"err":err,"ret":ret};
        data['branch'] = this.branch||'';
    if( this.output === "view" ){
        this.status = 200;
        if(err){
            this.view = "error";
        }
    }
    return data;
}



